//
//  TSZRefreshControl.swift
//  微博天下

import UIKit

//下拉刷新偏移量
private let refreshOffset: CGFloat =  -60

class TSZRefreshControl: UIRefreshControl {

    override init(){
        super.init()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK - 重写结束刷新
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoading()
    }
    
    //释放
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    //MARK -KVO 
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //如果 y?> 0
        
//        print(frame.origin.y)
        
        if frame.origin.y > 0 {
            return
        }
        //判断开始刷新
        if refreshing {
            refreshView.startLoading()
        }
        
        if frame.origin.y < refreshOffset && !refreshView.rotateFlag{
            refreshView.rotateFlag = true
            
        }else if frame.origin.y > refreshOffset  && refreshView.rotateFlag{
            refreshView.rotateFlag = false
        }
        
    }
    //布局UI
    private func setupUI(){
        // KVO 监听 frame 属性变化
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        //隐藏默认的转轮
        tintColor = UIColor.clearColor()
        //刷新新视图
        addSubview(refreshView)
        
        //自动布局 -- 从xib加载的时候，可以直接取到真是的大小
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    }
    /// 懒加载属性
    private lazy var refreshView: TSZRefreshView = TSZRefreshView.refreshView()
    
}

//MARK -xib的class
class TSZRefreshView: UIView{
    
    //旋转标记
    private var rotateFlag = false {
        didSet{
            rotateTipIcon()
        }
    }
    
    //MARK 控件的连线
    @IBOutlet weak var iconImage: UIImageView!
    
    @IBOutlet weak var textLabel: UILabel!
    
    @IBOutlet weak var TipView: UIView!
    
    @IBOutlet weak var tipIcon: UIImageView!
    //从xib加载刷新新视图
    class func refreshView() -> TSZRefreshView{
        return NSBundle.mainBundle().loadNibNamed("refreshView", owner: nil, options: nil).last as! TSZRefreshView
    }
    /**
    块代码动画
    */
    private func rotateTipIcon(){
        let angle = rotateFlag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01)
        //动画效果
        UIView.animateWithDuration(0.25) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
    }
    
    //开始加载动画
    private func startLoading() {
        //0、判断是否已经被添加
         if iconImage.layer.animationForKey("loadingAnimation") != nil {
            return
        }
        //1、隐藏提示试图，显示 那个菊花
        TipView.hidden = true
        
        //定义动画
        let anmi = CABasicAnimation(keyPath: "transform.rotation")
        anmi.toValue = 2 * M_PI
        anmi.duration = 1.0
        /**
        * 添加动画
        */
        iconImage.layer.addAnimation(anmi, forKey: "loadingAnimation")
    }
    
    //停止加载动画
    private func stopLoading() {
        TipView.hidden = false
        iconImage.layer.removeAllAnimations()
    }
    
}
